import axios from 'axios'
import qs from 'querystring'
import { message } from 'antd';
import NProgress from 'nprogress'
import store from '../redux/store.js';
import {createDeleteUserInfoAction} from '../redux/actions/login_action.js'

const instance = axios.create({
  timeout: 3000
});

// instance.defaults.headers.common['Authorization'] = 'atguigu_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkNmEyYTU2OTZiODExMjEzYzI2Yjg3ZiIsImlhdCI6MTU2NzM4ODUwOCwiZXhwIjoxNTY3OTkzMzA4fQ.XF42Fq6mESxStnAVEF-bmYEfAHDCvPMb__wkwOkyeOk';

// 请求拦截器
instance.interceptors.request.use(function (config) {
  // 进度条开始
  NProgress.start()
  
  // 从redux获取token
  const {token} = store.getState().userInfo
  if (token) {
    // 给请求头增加token
    config.headers.Authorization = 'atguigu_'+token
  }
  
  let {data, method} = config
  if (method.toLowerCase() === 'post' && data instanceof Object){
    config.data = qs.stringify(data)
  }
  return config;
});

// 响应拦截器
instance.interceptors.response.use(function (response) {
  // 进度条结束
  NProgress.done()
  return response.data;
}, function (error) {
  // 进度条结束
  NProgress.done()
  // 错误消息提示
  if (error.response.status === 401) {
    // 如果是token失效，会401错误，无权限
    message.error('身份校验失败，请重新登录', 1);
    // 删除localStorage中的token，让页面跳转到login页面
    store.dispatch(createDeleteUserInfoAction())
  } else {
    message.error(error.message, 1);
  }
  return new Promise(()=>{});
});

export default instance
